package com.magus.project.yddemo.controller;

import static org.springframework.http.HttpStatus.NOT_FOUND;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.annotation.JsonView;
import com.magus.framework.core.controller.BaseController;
import com.magus.framework.core.entity.BaseTreeNode.WithOutTreeView;
import com.magus.framework.core.exception.app.ControllerException;
import com.magus.framework.core.persistence.SearchFilter;
import com.magus.framework.core.util.lang.StringUtils;
import com.magus.framework.system.annotation.AppFunctionInfo;
import com.magus.framework.system.annotation.AppFunctionInfo.FunctionType;
import com.magus.framework.system.annotation.AppGroupInfo;
import com.magus.project.yddemo.entity.Indicator;
import com.magus.project.yddemo.entity.IndicatorGroup;
import com.magus.project.yddemo.service.IndicatorGroupService;
import com.magus.project.yddemo.service.IndicatorService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 指标管理
 * 
 * @author xujuan
 * @date 2018-01-19 15:26:53
 */
@Api(tags = "IndicatorManager", description = "指标管理")
@RestController
@RequestMapping("/yddemo/indicators")
@AppGroupInfo(key = "yddemo:indicator", name = "指标管理", appKey = "yddemo")
public class IndicatorController extends BaseController {

	@Autowired
	private IndicatorService indicatorService;

	@Autowired
	private IndicatorGroupService groupService;

	/**
	 * 根据ID查询指标信息
	 * 
	 * @param indicatorId
	 *            指标ID
	 * @return 指标信息
	 */
	@GetMapping("/{indicatorId}")
	@RequiresPermissions("yddemo:indicator:view")
	@ApiOperation(value = "查询指标", notes = "根据ID查询指标信息")
	ResponseEntity<Indicator> findOne(@PathVariable String indicatorId) {

		Indicator indicator = indicatorService.findOne(indicatorId);
		if (indicator == null) {
			return ResponseEntity.status(NOT_FOUND).body(null);
		}

		return ResponseEntity.ok(indicator);
	}

	/**
	 * 查询指标
	 * 
	 * @param groupId
	 *            指标组ID
	 * @return 指标组下面的指标集合
	 */
	@GetMapping(params = { "groupId" })
	@RequiresPermissions("yddemo:indicator:view")
	@ApiOperation(value = "查询指标", notes = "查询此指标组下面的指标")
	@AppFunctionInfo(key = "yddemo:indicator:view", name = "查询指标列表", groupKey = "yddemo:indicator", //
			isMenu = false, type = FunctionType.PAGE, url = "/yddemo/indicators/page/view")
	ResponseEntity<List<Indicator>> findAll(@RequestParam(required = false) String groupId) {
		if (groupId == null || "".equals(groupId)) {
			return ResponseEntity.ok(new ArrayList<Indicator>());
		}
		IndicatorGroup group = groupService.findOne(groupId);

		List<SearchFilter> searchFilters = new ArrayList<>();
		searchFilters.add(SearchFilter.equal("group", group));

		Specification<Indicator> spec = buildFilterRequest(searchFilters);

		List<Indicator> result = indicatorService.findAll(spec);
		return ResponseEntity.ok(result);
	}

	/**
	 * 新增
	 * 
	 * @param indicator
	 * @param result
	 * @return
	 */
	@JsonView(WithOutTreeView.class)
	@PostMapping
	@RequiresPermissions("yddemo:indicator:add")
	@ApiOperation(value = "新增指标", notes = "返回成功保存后的对象")
	@AppFunctionInfo(key = "yddemo:indicator:add", name = "新增指标", groupKey = "yddemo:indicator", //
			isMenu = false, type = FunctionType.PAGE, url = "/yddemo/indicators/page/add")
	ResponseEntity<Indicator> add(@RequestBody Indicator indicator, BindingResult result) {
		IndicatorGroup group = indicator.getGroup();
		if (group != null && StringUtils.isNotBlank(group.getId())) {
			group = groupService.findOne(group.getId());
			if (group == null) {
				throw new ControllerException("APP:SYSTEM:FUNCGROUP_ADD", "指标组没有找到",
						"ControllerException.system.appgroup.app_notfound");
			} else {
				indicator.setGroup(group);
			}
		}

		validate(indicator, result);
		Indicator saved = indicatorService.save(indicator);
		return ResponseEntity.status(HttpStatus.CREATED).body(saved);
	}

	/**
	 * 更新指标
	 * 
	 * @param indicatorId
	 *            指标ID
	 * @param indicator
	 *            修改的指标数据
	 * @param result
	 *            Spring Framework自已管理的参数
	 * @return 更新后的指标信息
	 */
	@PutMapping("/{indicatorId}")
	@RequiresPermissions("yddemo:indicator:edit")
	@ApiOperation(value = "编辑指标", notes = "返回成功保存后的对象")
	@AppFunctionInfo(key = "yddemo:indicator:edit", name = "编辑指标", groupKey = "yddemo:indicator", //
			isMenu = false, type = FunctionType.PAGE, url = "/yddemo/indicators/page/edit")
	ResponseEntity<Indicator> update(@PathVariable String indicatorId, @RequestBody Indicator indicator,
			BindingResult result) {
		Indicator old = indicatorService.findOne(indicatorId);
		if (old == null) {
			return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
		}
		indicator.setId(old.getId());

		IndicatorGroup group = indicator.getGroup();
		if (group != null && StringUtils.isNotBlank(group.getId())) {

			group = groupService.findOne(group.getId());
			if (group == null) {
				throw new ControllerException("APP:SYSTEM:FUNCGROUP_ADD", "指标组没有找到",
						"ControllerException.system.appgroup.app_notfound");
			} else {
				indicator.setGroup(group);
			}
		}

		validate(indicator, result);
		Indicator saved = indicatorService.save(indicator);
		return ResponseEntity.ok(saved);
	}

	/**
	 * 删除指标
	 * 
	 * @param ids
	 *            指标ID
	 * @return 无返回内容
	 */
	@DeleteMapping
	@RequiresPermissions("yddemo:indicator:delete")
	@ApiOperation(value = "删除指标", notes = "根据ID删除指标")
	@AppFunctionInfo(key = "yddemo:indicator:delete", name = "删除指标", groupKey = "yddemo:indicator", //
			isMenu = false, type = FunctionType.BUTTON, url = "/yddemo/indicators")
	ResponseEntity<Void> delete(@RequestBody List<String> ids) {
		List<SearchFilter> searchFilters = new ArrayList<>();
		searchFilters.add(SearchFilter.in("id", ids));

		Specification<Indicator> spec = buildFilterRequest(searchFilters);
		List<Indicator> indicators = indicatorService.findAll(spec);

		if (indicators == null || indicators.isEmpty()) {
			return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
		}
		indicatorService.delete(indicators);
		return ResponseEntity.noContent().build();
	}

}
